﻿using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

namespace Common
{
    public static class ReuseMethod
    {
        public static string GetUrlQuery(string Url,string key)
        {
            var query = new Uri(Url).Query;
            return QueryHelpers.ParseQuery(query).GetValueOrDefault(key).FirstOrDefault();
        }
        public static void AddAssembly(this IServiceCollection service, string assemblyName
            , ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
        {
            var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName));

            var types = assembly.GetTypes();
            var list = types.Where(u => !u.IsInterface && !u.IsGenericType && !u.IsAbstract).ToList();

            foreach (var type in list)
            {
                var interfaceList = type.GetInterfaces();
                foreach (var inter in interfaceList)
                {
                    switch (serviceLifetime)
                    {
                        case ServiceLifetime.Transient:
                            service.AddTransient(inter, type);
                            break;
                        case ServiceLifetime.Scoped:
                            service.AddScoped(inter, type);
                            break;
                        case ServiceLifetime.Singleton:
                            service.AddSingleton(inter, type);
                            break;
                    }
                }
            }
        }
    }
}
